package com.xyd.wechat.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.xyd.wechat.common.ApplicationConfig;
import com.xyd.wechat.common.Constant;
import com.xyd.wechat.common.MsgTypeEnum;
import com.xyd.wechat.mapper.ChatRobotUserMapper;
import com.xyd.wechat.model.ChatRobotUser;
import com.xyd.wechat.service.AccessTokenService;
import com.xyd.wechat.service.CustomerService;
import com.xyd.wechat.vo.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Calendar;

@Service
public class CustomerServiceImpl implements CustomerService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private AccessTokenService accessTokenService;

    @Autowired
    private ApplicationConfig applicationConfig;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private ChatRobotUserMapper chatRobotUserMapper;


    /**
     * 消息 转人工客服
     *
     * @param message
     * @return
     */
    @Override
    public Message transferCustomerService(Message message) {
        try {
            Message transferMessage = new Message();
            transferMessage.setMsgType(MsgTypeEnum.TRANSFER_CUSTOMER_SERVICE.getType());
            transferMessage.setFromUserName(message.getFromUserName());
            transferMessage.setToUserName(message.getToUserName());
            transferMessage.setCreateTime(Calendar.getInstance().getTimeInMillis());
            return transferMessage;
        } catch (Exception e) {
            logger.error("消息转人工客服异常。", e);
            return null;
        }
    }

    @Override
    public void sendToUser(Message message) {
        try {
            ObjectNode objectNode = objectMapper.createObjectNode();
            objectNode.put("touser", message.getToUserName());
            objectNode.put("msgtype", message.getMsgType());
            if (message.getMsgType().equals(MsgTypeEnum.TEXT.getType())) {
                // 发送文本消息，所需的JSON数据包
                ObjectNode contentNode = objectMapper.createObjectNode();
                contentNode.put("content", message.getContent());
                objectNode.set("text", contentNode);
            } else if (message.getMsgType().equals(MsgTypeEnum.IMAGE.getType())) {
                // 发送图片消息，所需的JSON数据包
                ObjectNode mediaNode = objectMapper.createObjectNode();
                mediaNode.put("media_id", message.getMediaId());
                objectNode.set("image", mediaNode);
            }
            // http请求方式: POST
            String url = String.format(applicationConfig.getWechatCustomSendUrl(), accessTokenService.getAccessToken());
            logger.info("客服接口-发消息-URL:{}", url);
            logger.info("客服接口-发消息-参数：{}", objectNode.toString());
            ResponseEntity<String> entity = restTemplate.postForEntity(url, objectNode.toString(), String.class);
            logger.info("客服接口-发消息  响应内容：{}", entity.getBody());
        } catch (Exception e) {
            logger.error("客服接口-发消息  发送文本消息", e);
        }
    }

    /**
     * 关闭客服会话，转入智能客服（聊天机器人）
     *
     * @param message
     */
    @Override
    public void closeDialogue(Message message) {
        try {
            String url = String.format(applicationConfig.getWechatCustomStatusUrl(), accessTokenService.getAccessToken(), message.getToUserName());
            logger.info("获取客户会话状态URL:{}", url);
            ResponseEntity<String> entity = restTemplate.getForEntity(url, String.class);
            logger.info("获取客户会话状态:{}", entity.getBody());
            JsonNode jsonNode = objectMapper.readTree(entity.getBody());
            String kfAccount = null;
            if (jsonNode.has("kf_account")) {
                kfAccount = jsonNode.get("kf_account").asText();
                url = String.format(applicationConfig.getWechatCustomCloseUrl(), accessTokenService.getAccessToken());
                logger.info("关闭会话URL:{}", url);
                ObjectNode objectNode = objectMapper.createObjectNode();
                objectNode.put("kf_account", kfAccount);
                objectNode.put("openid", message.getToUserName());
                entity = restTemplate.postForEntity(url, objectNode.toString(), String.class);
                logger.info("关闭会话:{}", entity.getBody());
            } else {
                logger.info("关闭客服会话，转入智能客服（聊天机器人）失败。{}", entity.getBody());
            }
        } catch (Exception e) {
            logger.error("关闭客服会话", e);
        }
    }

    /**
     * 客服对话结束 , 转入机器人对话模式
     *
     * @param message
     */
    @Override
    public void kfCloseSession(Message message) {
        ChatRobotUser chatRobotUser = new ChatRobotUser();
        chatRobotUser.setUsername(message.getToUserName());
        chatRobotUser.setSource(Constant.SOURCE_WX);
        ChatRobotUser user = chatRobotUserMapper.selectOne(chatRobotUser);
        if (user == null) {
            chatRobotUser.setStatus(Constant.Y);
            chatRobotUser.setCreatetime(Calendar.getInstance().getTime());
            chatRobotUserMapper.insertUseGeneratedKeys(chatRobotUser);
        } else {
            user.setStatus(Constant.Y);
            user.setUpdatetime(Calendar.getInstance().getTime());
            chatRobotUserMapper.updateByPrimaryKey(user);
        }
    }
}
